package com.sdy.healthcode.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.Response;
import com.sdy.common.utils.StringUtil;
import com.sdy.healthcode.biz.dto.PersonnelEntryAndExitDTO;
import com.sdy.healthcode.biz.dto.ThisCourtVO;
import com.sdy.healthcode.biz.model.Manager;
import com.sdy.healthcode.biz.service.ManagerService;
import com.sdy.healthcode.biz.service.ReportPeoplePassService;
import com.sdy.healthcode.biz.model.ReportPeoplePass;
import com.sdy.healthcode.biz.service.UserService;
import com.sdy.healthcode.web.vo.ManagerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sdy.mvc.controller.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 人员进出分析报表 前端控制器
 * </p>
 *
 * @author cgj
 * @since 2020-02-28
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/reportPeoplePass")
@Api(tags = "导出")
public class ReportPeoplePassController extends BaseController {
    @Autowired
    private ReportPeoplePassService reportPeoplePassService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private UserService userService;

    @GetMapping("/download")
    @ApiOperation(value = "人员管理页面的导出")
    public void download(HttpServletResponse response){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            List<ReportPeoplePass> list = reportPeoplePassService.list();
            String fileName = "Personnel entry and exit-"+date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            EasyExcel.write(response.getOutputStream(), ReportPeoplePass.class).sheet("人员进出分析表").doWrite(list);
        } catch (Exception e) {
            log.error("人员进出分析表下载失败"+e.getMessage(),e);
        }
    }

///    @GetMapping("/downloadStaff")
///    @ApiOperation(value = "本院人员数据导出")
///    public void downloadStaff(HttpServletResponse response, String name,Integer authScan){
///        try {
///            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
///            String date = sdf.format(new Date());
///            List<ThisCourtVO> list = userService.getPage(name, authScan, null);
///            for (ThisCourtVO l : list) {
///                if (l.getAuthScan().equals(1)) {
///                    l.setAuthScanStr("有");
///                } else {
///                    l.setAuthScanStr("无");
///                }
///                if (l.getAuthCockpit().equals(1)) {
///                    l.setAuthCockpitStr("有");
///                } else {
///                    l.setAuthCockpitStr("无");
///                }
///            }
///            String fileName = "Staff of our hospital-"+date + ".xlsx";
///            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
///            EasyExcel.write(response.getOutputStream(), ThisCourtVO.class).sheet("本院人员数据导出表").doWrite(list);
///        } catch (Exception e) {
///            log.error("本院人员数据表下载失败"+e.getMessage(),e);
///        }
///    }

    @GetMapping("/downAccountmana")
    @ApiOperation(value = "账号管理数据导出")
    public void downAccountmana(HttpServletResponse response, String phone){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            List<Manager> list = managerService.list(Wrappers.<Manager>lambdaQuery().like(StringUtil.isNotBlank(phone), Manager::getPhone, phone));
            List<ManagerVO> mvList = new ArrayList<>();
            for (Manager m : list) {
                ManagerVO managerVO = new ManagerVO();
                managerVO.setId(m.getId());
                managerVO.setName(m.getName());
                managerVO.setPhone(m.getPhone());
                if (m.getState() == 1) {
                    managerVO.setStateStr("启用");
                } else if (m.getState() == 2) {
                    managerVO.setStateStr("禁用");
                }
                managerVO.setState(m.getState());
                mvList.add(managerVO);
            }
            String fileName = "Account management-"+date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            EasyExcel.write(response.getOutputStream(), ManagerVO.class).sheet("账号管理表").doWrite(mvList);
        } catch (Exception e) {
            log.error("账号管理表下载失败"+e.getMessage(),e);
        }
    }

    @GetMapping("/getPerAnalysis")
    @ApiOperation(value = "人员进出情况分析数据表", response = PersonnelEntryAndExitDTO.class)
    public Response<List<PersonnelEntryAndExitDTO>> getPerAnalysis(){
        List<PersonnelEntryAndExitDTO> list = reportPeoplePassService.getEtryAndExitBase();
        for (int i = 0; i < list.size(); i++) {
            // 人员进入健康度数据处理
            String healthInNumAcc = getValue(list.get(i).getHealthInNum(), list.get(i).getInNum());
            list.get(i).setHealthInNumAcc(healthInNumAcc);
            // 人员出去健康度数据处理
            String healthOutNumAcc = getValue(list.get(i).getHealthOutNum(), list.get(i).getOutNum());
            list.get(i).setHealthOutNumAcc(healthOutNumAcc);
            // 进出次数数据处理
            int sumNum = list.get(i).getInNum() + list.get(i).getOutNum();
            list.get(i).setSumNum(sumNum);
            // 总体健康度数据处理
            String sumHealthNumAcc = getValue(list.get(i).getHealthInNum() + list.get(i).getHealthOutNum(), list.get(i).getSumNum());
            list.get(i).setSumHealthNumAcc(sumHealthNumAcc);
        }
        // 进入合计
        int inNum = list.stream().collect(Collectors.summingInt(PersonnelEntryAndExitDTO::getInNum));
        // 出去合计
        int outNum = list.stream().collect(Collectors.summingInt(PersonnelEntryAndExitDTO::getOutNum));
        // 健康人员进入合计
        int healthInNum = list.stream().collect(Collectors.summingInt(PersonnelEntryAndExitDTO::getHealthInNum));
        // 健康人员出去合计
        int healthOutNum = list.stream().collect(Collectors.summingInt(PersonnelEntryAndExitDTO::getHealthOutNum));
        // 人员进入健康度合计
        String healthInNumAcc = getValue(healthInNum, inNum);
        // 人员出去健康度合计
        String healthOutNumAcc = getValue(healthOutNum, outNum);
        // 进出总次数
        int sumNum = inNum + outNum;
        // 总体健康度数据
        String sumHealthNumAcc = getValue(healthInNum + healthOutNum, sumNum);
        list.add(new PersonnelEntryAndExitDTO().setInNum(inNum).setOutNum(outNum).setHealthInNumAcc(healthInNumAcc)
                .setHealthOutNumAcc(healthOutNumAcc).setSumNum(sumNum).setSumHealthNumAcc(sumHealthNumAcc));
        return Response.success(list);
    }

    public static String getValue(Integer dividend, Integer divisor) {
        if (divisor == 0) {
            return "100%";
        }
        DecimalFormat df=new DecimalFormat("0.0000");
        DecimalFormat cf = new DecimalFormat("0.00%");
        String format = cf.format(Float.parseFloat(df.format((float) dividend / divisor))) ;
        return format;
    }

}
